const app = getApp();
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    open_id: '',
    runData: [],
    phone: '',
    modalName: '',
    sessionKey: '',
    declare: '',
    prize: '',
    hdgz: '',
    shareText: '',
    title: '',
    isCard: false,
    visit_count: 0,
    like_count: 0,
    user_count: 0,
    swiperList: [],
    sites: [],
    TabCur: 0,
    site_id: 340100,
    scrollLeft: null,
    w: null,
    h: null,
    main: null,
  },
  onLoad() {

    try {
      const res = wx.getSystemInfoSync()

      let c1 = 180 / 750 * res.windowWidth;

      let p1 = 20 * 0.5
      let p2 = 20 * 0.5

      let w = (res.windowWidth - p1 - p2) /2
      let w1 = (w / 4)
      let h = (w1 * 3)

      this.setData({
        w: w,
        h: h,
        main: (h + c1),
      })
    } catch (e) {
      // Do something when catch error
    }

    wx.showShareMenu({
      withShareTicket: true
    })

    const cityCode = wx.getStorageSync('cityCode');
    const sessionKey = wx.getStorageSync('sessionKey');
    const open_id = wx.getStorageSync('user_new');
    const phone = wx.getStorageSync('phone');
    const declare = wx.getStorageSync('declare');

    if (cityCode) {
      this.setData({
        site_id: cityCode
      })
    }
    if (declare) {
      this.setData({
        declare: declare,
      })
    }

    this.setData({
      open_id: open_id,
      phone: phone,
      sessionKey: sessionKey,
    })

    this.getDataList()
    this.getSites()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: this.data.shareText,
      path: '/pages/vote/index'
    }
  },

  onPullDownRefresh: function() {
    this.getDataList()
    setTimeout(() => {
      wx.showToast({
        title: '刷新成功'
      })
      wx.stopPullDownRefresh()
    }, 1000)

    return true;
  },

  getDataList() {
    const that = this
    app.core('get', '315/vote?site_id=' + this.data.site_id, {}, (res) => {
      if (res.resultCode == 200) {
        that.setData({
          runData: res.data,
          prize: res.prize,
          hdgz: res.hdgz,
          title: res.title,
          visit_count: res.visit_count,
          like_count: res.like_count,
          user_count: res.user_count,
          swiperList: res.tops,
        })

        if (res.shareText != '') {
          that.setData({
            shareText: res.shareText
          })
        }

        if (res.declare != '' && that.data.declare == '') {
          that.setData({
            declare: res.declare
          })
        }
      }
    })
  },

  handleContent: function () {
    wx.previewImage({
      current: this.data.hdgz,
      urls: [
        this.data.hdgz,
      ]
    })
  },

  handlePrize: function () {
    wx.previewImage({
      current: this.data.prize,
      urls: [
        this.data.prize,
      ]
    })
  },

  getPhoneNumber (e) {
    const that = this
    if (e.detail.iv && e.detail.encryptedData) {
      app.core('post', 'user/getPhoneNumber', {encrypted_data: e.detail.encryptedData, iv: e.detail.iv, open_id: this.data.open_id}, (res) => {
        if (res.resultCode == 200) {
          if (res.data.purePhoneNumber) {
            wx.setStorageSync("phone", res.data.purePhoneNumber)
            that.setData({
              phone: res.data.purePhoneNumber
            })
          } else {
            wx.showToast({
              title: '获取手机号失败',
            })
          }
        } else {
          wx.showToast({
            title: '获取手机号失败',
          })
        }
      })
    } else {
      wx.showToast({
        title: '获取手机号失败',
      })
    }
  },

  toLogin: function () {
    wx.reLaunch({
      url: '/pages/member/index?redirect=' + encodeURIComponent('/pages/runData/index')
    })

    return false
  },

  handleExpose() {
    wx.navigateTo({
      url: '/pages/expose/index'
    })
  },

  handleBack() {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },

  preview(e) {
    wx.previewImage({
      urls: e,
      current: this.data.swiperList
    });
  },

  tabSelect(e) {
    console.log(e.currentTarget.dataset.site_id)
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id-1)*60,
      site_id: e.currentTarget.dataset.site_id
    })

    this.getDataList()
  },

  advJump (e) {

    let swiperList = this.data.swiperList

    let val = swiperList[e.currentTarget.dataset.index]
    if (val) {
      if ( val['app_id'] != undefined && val['app_id'] != null && val['app_id'] != '') {
        wx.navigateToMiniProgram({
          appId: val['app_id'],
          path: val['redirect_url'],
          extraData: {},
          envVersion: 'release',
          success(res) {
            console.log(res)
            // 打开成功
          },
          fail(e) {
            console.log(e)
          }
        })
      } else if ( val['redirect_url'] != undefined && val['redirect_url'] != null && val['redirect_url'] != '') {

        let url = val['redirect_url']

        if (url.indexOf("/pages") == 0) {
          wx.navigateTo({
            url: url,
          })
        } else if (url.indexOf("http") == 0) {
          wx.navigateTo({
            url: '/pages/webView/index?url='+ decodeURIComponent(url),
          })
        }
      }

    }
  },

  handleVote(e) {
    let id = e.target.dataset.id
    const that = this

    let open_id = wx.getStorageSync('user_new')
    if  (open_id == undefined || open_id == '') {
      wx.showModal({
        title: '提示',
        content: '本功能需要授权后才可使用，点击确定跳转到登录界面',
        success(res) {
          if (res.confirm) {
            setTimeout(() =>{

              wx.reLaunch({
                url: '/pages/member/index?redirect=' + encodeURIComponent('/pages/vote/index')
              })

            }, 500)
          } else if (res.cancel) {
          }
        }
      })

      return false
    }

    app.core('get', '315/voteAdd', {open_id: open_id, id: id}, (res) => {
      if (res.resultCode == 200) {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })

        let data = that.data.runData
        for (var i = 0; i < data.length; i++) {
           if (data[i]['id'] == id) {
             data[i]['likes'] = data[i]['likes'] + 1
           }
        }
        that.setData({
          runData: data,
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },

  getSites() {
    const that = this
    app.core('get', '315/sites', {}, (res) => {
      that.setData({
        sites: res.data,
      });

      let data = res.data
      for (var i = 0; i < data.length; i++) {
        if (data[i]['id'] == that.data.site_id) {
         that.setData({
           TabCur: i
         })
        }
      }
    })
  }

})
